import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateArticleCommentDto } from './dtos/create-article-comment.dto'
import { InjectRepository } from '@nestjs/typeorm'
import { IsNull, Repository } from 'typeorm'
import { Article } from '../../entities/article.entity'
import { ArticleMoment } from '../../entities/articleMoment.entity'
import { User } from '../../entities/user.entity'
import { SearchDto } from 'src/dtos/search.dto';
import { PageResult } from '../../type/result'



@Injectable()
export class ArticleCommentService {

    constructor(
        @InjectRepository(Article)
        private readonly articleRepository: Repository<Article>,
        @InjectRepository(ArticleMoment)
        private readonly articleMomentRepository: Repository<ArticleMoment>,
        @InjectRepository(User)
        private readonly userRepository: Repository<User>

    ) { }

    async findAll(article_id: string, searchDto: SearchDto) {
        const page = Number(searchDto.page)
        const limit = Number(searchDto.limit)

        // 查询文章是否存在
        const articles = await this.articleMomentRepository.find({
            where: {
                article: {
                    article_id
                },
                parentMoment: IsNull()
            },
            skip: (page - 1) * limit,
            take: limit,
            relations: ['author']
        })

        // 查询是否有子评论
        const childrenCounts = await Promise.all(
            articles.map(async item => ({
                id: item.id,
                childrenCount: await this.articleMomentRepository.count({
                    where: {
                        parentMoment: {
                            id: item.id
                        }
                    }
                })
            }))
        )

        // 合并子类数据
        const list = articles.map(item => ({
            ...item,
            childrenCount: childrenCounts.find(c => c.id === item.id).childrenCount || 0,
            children: []
        }))

        // 查询一级评论条数
        const total = await this.articleMomentRepository.count({
            where: {
                article: {
                    article_id
                },
                parentMoment: IsNull()
            },
        })
        return {
            limit,
            page,
            list,
            total,
        }
    }
    async findAllReplay(parent_id: string, searchDto: SearchDto) {
        const page = Number(searchDto.page)
        const limit = Number(searchDto.limit)

        console.log(parent_id)
        const list = await this.articleMomentRepository.find(
            {
                where: {
                    parentMoment: {
                        id: parent_id
                    }
                },
                relations: ['author', 'replayUser'],
                skip: (page - 1) * limit,
                take: limit
            }

        )
        const total = await this.articleMomentRepository.count({
            where: {
                parentMoment: {
                    id: parent_id
                }
            }
        })
        // 查询
        return {
            page,
            limit,
            list,
            total
        }
    }

    async create(userId: string, createArticleCommentDto: CreateArticleCommentDto) {
        const articleMoment = new ArticleMoment()
        const user = await this.userRepository.findOne({ where: { id: userId } });

        // 查询文章是否存在
        const article = await this.articleRepository.findOne({ where: { article_id: createArticleCommentDto.article_id } });

        if (article === null) {
            throw new HttpException('文章不存在', HttpStatus.BAD_REQUEST);
        }

        // 查询父评论是否存在（仅当传入了 parentMoment 时）
        let parentMoment: ArticleMoment | null = null;
        let replayUser: User | null = null;
        if (createArticleCommentDto.parent_id) {
            parentMoment = await this.articleMomentRepository.findOne({ where: { id: createArticleCommentDto.parent_id } });

            if (!parentMoment) {
                throw new HttpException('评论不存在', HttpStatus.BAD_REQUEST);
            }
            if (createArticleCommentDto.replay_id) {
                replayUser = await this.userRepository.findOne({ where: { id: createArticleCommentDto.replay_id } });
                if (!replayUser) {
                    throw new HttpException('回复用户不存在', HttpStatus.BAD_REQUEST);
                }
            }
        }

        articleMoment.author = user
        articleMoment.article = article
        articleMoment.moment = createArticleCommentDto.moment
        articleMoment.status = 1 // 默认为一，被举报了设置为 0待审核
        articleMoment.parentMoment = parentMoment
        articleMoment.replayUser = replayUser

        return await this.articleMomentRepository.save(articleMoment)
    }
}
